package model

import (
	"database/sql/driver"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	pkg "sunliang.cc/package"
	"time"
)

type LocalTime struct {
	time.Time
}

func (t *LocalTime) MarshalJSON() ([]byte, error) {
	output := fmt.Sprintf("\"%s\"", t.Format(time.DateTime))
	return []byte(output), nil
}

func (t *LocalTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

func (t *LocalTime) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = LocalTime{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}

var db *gorm.DB

type Model struct {
	ID int `gorm:"primary_key" json:"id"`
}

func DatabaseInit() {
	var err error

	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s",
		pkg.DbSetting.User,
		pkg.DbSetting.Password,
		pkg.DbSetting.Host,
		pkg.DbSetting.DbName,
	)
	dsn = dsn + "?charset=utf8mb4&parseTime=True&loc=Local"
	// 数据库连接
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("database init err: %v", err)
	}

	// 数据库连接池配置
	myConnectorSqlDB, err := db.DB()
	if err != nil {
		log.Fatalf("database db err: %v", err)
	}
	// 空闲连接池中连接的最大数量
	myConnectorSqlDB.SetMaxIdleConns(1)
	// 打开数据库连接的最大数量
	myConnectorSqlDB.SetMaxOpenConns(10)
	// 连接可复用的最大时间。
	myConnectorSqlDB.SetConnMaxLifetime(time.Second * 60)
}

func CloseDB() {
	sqlDB, _ := db.DB()
	defer sqlDB.Close()
}
